<?php

    function GeoListingFormFieldsHook($View,$formHelper,$listingData = null, $showFields=null)
    {
        if(!cr("MapConfig.show_form_map"))
        {
            return;
        }
        $region = '';
        if(cr('Geo.region'))
        {
            $region = 'region='.cr('Geo.region');
        }
        $locationFields = cri("MapConfig")->getLocationFields();
        if(!$showFields || !is_array($showFields))
        {
        	return;
        }
        $listingLocationFields = array_intersect($locationFields, $showFields);
        if(empty($listingLocationFields))
        {
        	return;
        }
        
        $View->listingFormHtml .= $formHelper->input("lat",array("type"=>"hidden"));
        $View->listingFormHtml .= $formHelper->input("lng",array("type"=>"hidden"));
        
        $moveMessage = "";
        if($listingData)
        {
            $moveMessage = $View->loaded['html']->link(__("Move pointer to default location"),'#',array("id"=>"moveToDefaultPos"));
        }
        $mapWrapper =<<<END
            <div id="add_form_mapWrapper">
                <div class="map_canvas" style="width: 400px;height: 300px;display: none">
                </div>
                 $moveMessage   
            </div>
END;
        $View->listingFormHtml .= $mapWrapper;
        $locationFieldJson = json_encode($locationFields);
        $lat = json_encode(@$listingData['Listing']['lat']);
        $lng = json_encode(@$listingData['Listing']['lng']);
		$popupMessage = json_encode("Drop marker to change location on map");
        $js=<<<END
            <script type="text/javascript">
            var makeMap = function()
            {
                var locationFields = $locationFieldJson;
                var selectorArr = [];
                for(var i in locationFields)
                {
                    selectorArr.push("[name='data[Listing]["+locationFields[i]+"]']");
                }
                if(selectorArr.length > 0)
                {
	                var selectorString = selectorArr.join(",");
					console.log(selectorString);
	                var positionElement = $(selectorString).filter(':last');
	                $('#add_form_mapWrapper').width($(positionElement).width());
	                var mapHtml = $('#add_form_mapWrapper').outerHTML();
	                $('#add_form_mapWrapper').remove();
	                positionElement.parent().after(mapHtml);
	            }
                var defaultLng = $lng;
                var defaultLat = $lat;    
                var MapObject = new locationFinderMap('lat','lng',locationFields,'Listing',
                $("#add_form_mapWrapper").children(".map_canvas"),defaultLat,defaultLng,$popupMessage);
                $("#moveToDefaultPos").click(function(){
                        MapObject.setToDefault();
                });
            }
            $(document).ready(function(){
                if(typeof locationFinderMap != "undefined" && typeof google.maps.Map != "undefined")
                {
                    setTimeout(function(){
                         makeMap();
                    },200)
                   
                }else
                {
                    setTimeout(function check(){
                        if(typeof locationFinderMap != "undefined" && typeof google.maps.Map != "undefined")
                        {
                            makeMap();
                        }else
                        {
                            setTimeout(check,700);
                        }
                    },700)
                }
                
            })
            </script>
END;
        $View->listingFormHtml .= $js;
        $isAjax = $View->params['isAjax'];
        $googleFile = 'http://maps.google.com/maps/api/js?sensor=false&'.$region;
        $geoMap = "/js/geomap.js";
        if(!$isAjax)
        {
            $View->loaded['javascript']->link($googleFile,false);
            $View->loaded['javascript']->link($geoMap,false);
        }else
        {
            $files = array($googleFile.'&callback=onGmapFileLoad',$View->loaded['html']->url($geoMap));
            $files = json_encode($files);
            $filesJs =<<<END
             <script type="text/javascript">
            var files = $files;
            function onGmapFileLoad()
            {
                console.log("Files loaded")
            }
            var appendFile = function(url)
            {
                var script = document.createElement("script");
                script.setAttribute("type","text/javascript");
                script.setAttribute("src",url);
                var head = document.getElementsByTagName("head")[0].appendChild(script);
                
            }
            if((typeof window.mapFilesLoaded == "undefined" || !window.mapFilesLoaded) && typeof locationFinderMap == "undefined") 
            {
                for(var i in files)
                {
                   appendFile(files[i]);
                }
                window.mapFilesLoaded = true;
            }
            </script>
END;
            $View->listingFormHtml .= $filesJs;
            
        }
    }
?>